<?php
declare (strict_types = 1);

namespace app\common\validate;

use think\Validate;
use app\common\model\user\SignForm;

class Register extends Validate
{
	protected $rule = [
        'username'          => 'require|max:15|unique:user,username',
        'email'             => 'require|max:64|unique:user,email|email',
        'captcha'           => 'require|print|checkCaptcha',
        'password'          => 'require|min:6',
        're_password'       => 'require|confirm:password',
    ];

    protected $message = [
        'username.require' => '用户名必须',
        'username.max'     => '用户名最多不能超过15个字符',
        'username.unique'  => '用户名已经存在',


        'email.require' => '邮箱必须',
        'email.max'     => '邮箱最多不能超过64个字符',
        'email.email'   => '邮箱格式错误',
        'email.unique'  => '邮箱已被占用',

        'captcha.require' => '验证码必须',
        'captcha.print'   => '验证码无效',
        'captcha.checkCaptcha' => '验证码无效',

        'password.require'      => '密码必须',
        'password.min'          => '密码最小为6个字符',
        're_password.min'       => '重复密码必须',
        're_password.confirm'   => '两次密码不一致',
    ];


    /**
     * 验证邮箱验证码是否有效
     * @param string $value post提交的验证码
     * @return bool
     */
    public function checkCaptcha($value, $rule, $formData=[]){

        //获取session验证码数据
        $email_key = SignForm::EMAIL_CAPTCHA_KEY;
        $session = app()->session;
        $data = $session->get($email_key,'');

        //没有验证数据
        if (empty($data)){
            return false;
        }

        //判断邮箱是否匹配
        if ($data['email'] !== $formData['email']){
            return false;
        }

        //判断时间
        if((time() - $data['lifetime']) > $data['start_at']){
            return false;
        }

        //判断是否一致
        if(strtoupper($data['captcha']) !== strtoupper($value)){
            return false;
        }

        //清空captcha
        $session->delete($email_key);
        return true;
    }


}
